import {
	getLoginInfo
} from '@/xiaoyun/api/user.js'

function getUserInfo() {
	return new Promise((resolve, reject) => {
		uni.getUserInfo({
			desc: '用于完善会员资料', // 此描述会显示给用户，说明获取用户信息的用途
			success: (res) => {
				resolve(res.userInfo);
			},
			fail: (err) => {
				reject('获取用户信息失败：' + JSON.stringify(err));
			}
		});
	});
}

// 服务端接口 - 获取openid
function queryOpenIdFn(code) {
	return new Promise((resolve, reject) => {
		loginFn().then(code => {
			getLoginInfo(code).then(res => {
				console.log('获取openid-res：', res);
				if (res.data) {
					uni.setStorageSync('chamberlain_open_id', res.data.openid)
					uni.setStorageSync('chamberlain_access_token', res.data.access_token)
					uni.setStorageSync('chamberlain_session_key', res.data.session_key)
					console.log('res.data.openid2', res.data.openid);
				}
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		}).catch(err => {
			reject(err)
		})
	})
}

// 微信api : 微信登录 获取code
function loginFn() {
	// let openId = uni.getStorageSync('chamberlain_open_id')
	// if (openId) return console.log('已获取openId',openId);
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: async (res) => {
				// console.log('登录res',res);
				resolve(res.code)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

export {
	loginFn,
	queryOpenIdFn,
	getUserInfo
}